package com.example.letswalk.shiro;

import com.example.letswalk.service.RoleService;
import org.apache.log4j.Logger;
import com.example.letswalk.pojo.SysUser;
import com.example.letswalk.service.SysMenuService;
import com.example.letswalk.service.SysUserService;
import com.example.letswalk.util.MyDES;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * MyShiroRealm 类
 * 授权用户权限和登录认证
 * author:wangwei
 */

public class MyShiroRealm extends AuthorizingRealm{

    @Autowired
    private SysMenuService sysMenuService;


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RoleService roleService;

    @Autowired
    SysUserService sysUserService;

    //用户登录次数计数  redisKey 前缀
    private String SHIRO_LOGIN_COUNT = "shiro_login_count_";

    //用户登录是否被锁定    一小时 redisKey 前缀
    private String SHIRO_IS_LOCK = "shiro_is_lock_";


    /**
    *   Author：wangwei
    *   查询用户权限和角色
    *   当进行权限管理的时候执行doGetAuthorizationinfo （）；
    * */
    @java.lang.Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //能进入到这里，表示账号已经通过验证了
        System.out.println(  principalCollection.getPrimaryPrincipal());
        String userName =(String) principalCollection.getPrimaryPrincipal();

        //通过service获取角色和权限
        Set<String> permissions = sysMenuService.listPermissions(userName);
        Set<String> roles = roleService.listRoleNames(userName);

        //授权对象
        SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
        //把通过service获取到的角色和权限放进去
        s.setStringPermissions(permissions);
        s.setRoles(roles);
        return s;
    }
    /**
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     *  当进行.login()方法的时候回去调用doGetAuthenticationinfo（）；
     * @auther wangwei
     */
    @java.lang.Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //获取账号密码
        UsernamePasswordToken t = (UsernamePasswordToken) authenticationToken;
       // String userName= authenticationToken.getPrincipal().toString();
        String userName =t.getUsername();
        //获取数据库中的密码
        SysUser user =sysUserService.getByName(userName);
        String passwordInDB = user.getPassword();



        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nickname", userName);
        map.put("pswd", passwordInDB);

        // 从数据库获取对应用户名密码的用户
       SysUser sysuser = sysUserService.selectByMap(map);

       // t.setRememberMe(true);


        Logger.getLogger(getClass()).info("身份认证成功，登录用户："+userName);
//        return new SimpleAuthenticationInfo(sysuser, MyDES.encryptBasedDes(passwordInDB), getName());
        return new SimpleAuthenticationInfo(sysuser, t.getPassword(), getName());
    }
}
